import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { Toast } from '@ionic-native/toast';

declare var $ :any;
@Component({
  selector: 'page-preview',
  templateUrl: 'preview.html'
})
export class PreviewPage {
  private img :any = {'w':undefined,'h':undefined,'dataUrl':undefined,'albumname':''}
  // private w :any
  // private h :any
  private flag:number = 0
  private database :SQLiteObject
  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private sqlite: SQLite,
              private toast: Toast) {
    this.database = this.navParams.data.database;
  }


  ionViewDidEnter(){
    this.putImage();
  }

  /**
   * 展示预览图片
   * 
   * @memberof PreviewPage
   */
  putImage() {
    var data = this.navParams.data
    $('#preview').append(data.result);
    this.img.w = data.result.width
    this.img.h = data.result.height
    this.img.albumname = data.albumname
  }

  /**
   * 将图片数据保存到本地数据库
   * 
   * @memberof PreviewPage
   */
  save2local() {
    if(this.flag === 0){
      var saveEare = $('canvas')[0];
      var dataUrl = saveEare.toDataURL('image/jpg');
      this.img.dataUrl = dataUrl;
      this.insert(this.img);
      this.flag++;
    }else {
      this.toast.show('您已经暂存了图片，无需再次暂存。','3000','center').subscribe();
    }
  }

  /**
   * 插入数据
   * 
   * @param {any} params 
   * @memberof PreviewPage
   */
  insert(params){
    var date: string = new Date().toLocaleDateString();
    var time: string = new Date().toTimeString().substring(0,5);
    var datetime: string = date + " " + time;
    console.log(datetime);
    this.database.executeSql("INSERT INTO kj_imgs (width,height,dataUrl,albumname) VALUES (?,?,?,?)",[params.w,params.h,params.dataUrl,params.albumname])
    .then((res) => {
      this.toast.show('暂存成功','3000','center').subscribe();
      console.log(res); console.log(this.database);  
    })
    .catch(e => console.log(e));
  }

}